package com.suyin.ximoon.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Timer;

public class GenericsUtils {

	/**
	 * 得到父类泛型参数的实际类型
	 * 
	 * 
	 * @param clazz
	 *            c 需要反射的类,该类必须继承范型父类
	 * @param index
	 *            泛型参数所在索引,从0开始.
	 * @return 范型参数的实际类型, 如果没有实现ParameterizedType接口，即不支持泛型，所以直接返回<code>Object.class</code>
	 */

	public static Class getSuperClassGenericType(Class c, int index) {
		Type type = c.getGenericSuperclass();
		// 判断是否属于泛型
		if (!(type instanceof ParameterizedType)) {
			return Object.class;
		}
		// 返回表示此类型实际类型参数的Type对象的数组,数组里放的都是对应类型的Class, 如BuyerServiceBean extends
		// DaoSupport<Buyer,Contact>就返回Buyer和Contact类型
		Type[] ptypes = ((ParameterizedType) type).getActualTypeArguments();
		if (index < 0 || ptypes.length < index) {
			throw new RuntimeException("无效的序号");
		}
		if (!(ptypes[index] instanceof Class)) {
			return Object.class;
		}
		return (Class) ptypes[index];
	}

	public static Class getSuperClassGeneriacType(Class c) {
		return getSuperClassGenericType(c, 0);
	}

	public static Boolean isCollection(Object collection) {
		boolean result = false;
		if (collection != null) {
			result = Collection.class.isAssignableFrom(collection.getClass());
		}
		return result;
	}

	public static Boolean isArray(Object array) {
		boolean result = false;
		if (array != null) {
			result = array.getClass().isArray();
		}
		return result;
	}
	
}
